/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.dtgenerator.api.entityInterface.resourceInfo;

import com.inspur.edp.bef.bizentity.GspBizEntityElement;
import com.inspur.edp.bef.bizentity.GspBizEntityObject;
import com.inspur.edp.caf.generator.utils.ExpressionUtils;
import com.inspur.edp.cef.api.repository.GspDbDataType;
import com.inspur.edp.cef.designtime.api.IGspCommonDataType;
import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.generator.apiGenerator.dataType.entityInterface.DataTypeInterfaceGeneratorContext;
import com.inspur.edp.cef.generator.apiGenerator.dataType.entityInterface.resourceInfo.initcolumnsstragety.BaseExtendAddPropertyInfoProcessor;
import com.inspur.edp.cef.generator.repository.entity.methods.InitColumnInfoMethodGenerator;
import com.inspur.edp.lcm.databaseobject.api.DatabaseObjectServiceForWebIde;
import com.inspur.edp.udt.designtime.api.entity.ComplexDataTypeDef;
import com.inspur.edp.udt.designtime.api.entity.SimpleDataTypeDef;
import com.inspur.edp.udt.designtime.api.entity.UnifiedDataTypeDef;
import com.inspur.edp.udt.designtime.api.entity.dbInfo.ColumnMapType;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.databaseobject.api.entity.DatabaseObjectColumn;
import io.iec.edp.caf.databaseobject.api.entity.DatabaseObjectTableCore;
import org.eclipse.jdt.core.dom.AST;

import java.util.List;

public class BefExtendAddPropertyInfoProcessor extends BaseExtendAddPropertyInfoProcessor {

  private DatabaseObjectServiceForWebIde dboService;

  private DatabaseObjectServiceForWebIde getDboService() {
    if (dboService == null) {
      dboService = SpringBeanUtils.getBean(DatabaseObjectServiceForWebIde.class);

    }
    return dboService;
  }
  @Override
  public void addComplexExtendPropertyArgs(List args, IGspCommonField field,
    IGspCommonDataType commonDataType,DataTypeInterfaceGeneratorContext parentContext, AST ast)
{

  if(isSimpleUdt(field,parentContext)||isComplextMutiToOneUdt(field,parentContext))
  {
    GspBizEntityObject bizEntityObject= (GspBizEntityObject) commonDataType;
    GspBizEntityElement bizEntityElement= (GspBizEntityElement) field;
    GspDbDataType dbDataType=GspDbDataType.VarChar;
    String dbColumnName="";
    if(bizEntityObject.getIsVirtual()==false&&bizEntityElement.getIsVirtual()==false)
    {
      DatabaseObjectTableCore databaseObject= (DatabaseObjectTableCore) getDboService().getDatabaseObjectById(parentContext.getApiGenContext().getCefGenContext().getMetadataPath(),bizEntityObject.getRefObjectName());
      DatabaseObjectColumn column= databaseObject.getColumnById(bizEntityElement.getColumnID());
      dbDataType= InitColumnInfoMethodGenerator.transDataType(column.getDataType());
      dbColumnName= column.getCode();
    }
    if(dbColumnName==null)
      dbColumnName="";
    args.add(ExpressionUtils
        .getQualifiedName(ast, "GspDbDataType", String.valueOf(dbDataType)));
    args.add(ExpressionUtils.getStringLiteral(ast,dbColumnName));
  }
  else {

    GspBizEntityObject bizEntityObject = (GspBizEntityObject) commonDataType;
    GspBizEntityElement bizEntityElement = (GspBizEntityElement) field;
    GspDbDataType dbDataType = GspDbDataType.VarChar;
    String dbColumnName = "";
    if (bizEntityObject.getIsVirtual() == false && bizEntityElement.getIsVirtual() == false) {
      DatabaseObjectTableCore databaseObject = (DatabaseObjectTableCore) getDboService()
          .getDatabaseObjectById(
              parentContext.getApiGenContext().getCefGenContext().getMetadataPath(),
              bizEntityObject.getRefObjectName());
      DatabaseObjectColumn column = databaseObject.getColumnById(bizEntityElement.getColumnID());
      dbDataType = InitColumnInfoMethodGenerator.transDataType(column.getDataType());
      dbColumnName = column.getCode();
    }
    if (dbColumnName == null)
      dbColumnName = "";
    parentContext.getApiGenContext().addImport(GspDbDataType.class.getTypeName());
    args.add(ExpressionUtils
        .getQualifiedName(ast, "GspDbDataType", String.valueOf(dbDataType)));
    args.add(ExpressionUtils.getStringLiteral(ast, dbColumnName));
  }
}

  @Override
  public void addSimpleExtendPropertyArgs(List args, IGspCommonField field,
      IGspCommonDataType commonDataType, DataTypeInterfaceGeneratorContext parentContext, AST ast) {
    if(isSimpleUdt(field,parentContext)||isComplextMutiToOneUdt(field,parentContext))
    {
      GspBizEntityObject bizEntityObject= (GspBizEntityObject) commonDataType;
      GspBizEntityElement bizEntityElement= (GspBizEntityElement) field;
      GspDbDataType dbDataType=GspDbDataType.VarChar;
      String dbColumnName="";
      if(bizEntityObject.getIsVirtual()==false&&bizEntityElement.getIsVirtual()==false)
      {
        DatabaseObjectTableCore databaseObject= (DatabaseObjectTableCore) getDboService().getDatabaseObjectById(parentContext.getApiGenContext().getCefGenContext().getMetadataPath(),bizEntityObject.getRefObjectName());
        DatabaseObjectColumn column= databaseObject.getColumnById(bizEntityElement.getColumnID());
        dbDataType= InitColumnInfoMethodGenerator.transDataType(column.getDataType());
        dbColumnName= column.getCode();
      }
      if(dbColumnName==null)
        dbColumnName="";
      args.add(ExpressionUtils
          .getQualifiedName(ast, "GspDbDataType", String.valueOf(dbDataType)));
    }
    else
      super.addSimpleExtendPropertyArgs(args,field,commonDataType,parentContext,ast);
  }

  private boolean isComplextMutiToOneUdt(IGspCommonField field,
      DataTypeInterfaceGeneratorContext parentContext) {
    if(field.getIsUdt()==false)
      return false;
    UnifiedDataTypeDef udtDef = (UnifiedDataTypeDef) parentContext.getApiGenContext().getCefGenContext().
        getMetadataJitContext().getMetadata(field.getUdtID()).getContent();
    if(udtDef instanceof ComplexDataTypeDef==false)
      return false;
    return ((ComplexDataTypeDef)udtDef).getDbInfo().getMappingType()== ColumnMapType.SingleColumn;
  }

  private boolean isSimpleUdt(IGspCommonField field,
      DataTypeInterfaceGeneratorContext parentContext) {
    if(field.getIsUdt()==false)
      return false;
    UnifiedDataTypeDef udtDef = (UnifiedDataTypeDef) parentContext.getApiGenContext().getCefGenContext().
        getMetadataJitContext().getMetadata(field.getUdtID()).getContent();
    return udtDef instanceof SimpleDataTypeDef;
  }

  @Override
  public boolean isDefaultNull(IGspCommonField field) {
    return ((GspBizEntityElement)field).getIsDefaultNull();
  }

  @Override
  public boolean useSimpleAddStatement(IGspCommonDataType commonDataType,
      IGspCommonField field,DataTypeInterfaceGeneratorContext parentContext) {
    GspBizEntityObject bizEntityObject= (GspBizEntityObject) commonDataType;
    GspBizEntityElement bizEntityElement= (GspBizEntityElement) field;
    GspDbDataType dbDataType=GspDbDataType.VarChar;
    String dbColumnName="";
    if(bizEntityObject.getIsVirtual()==false&&bizEntityElement.getIsVirtual()==false)
    {
      DatabaseObjectTableCore databaseObject = (DatabaseObjectTableCore) getDboService().getDatabaseObjectById(parentContext.getApiGenContext().getCefGenContext().getMetadataPath(), bizEntityObject.getRefObjectName());
      if (databaseObject == null) {
        throw new RuntimeException("缺少dbo文件，请重新保存BE生成dbo。BE编号：" + bizEntityObject.getCode() + "，BE名称：" + bizEntityObject.getName());
      }
      DatabaseObjectColumn column= databaseObject.getColumnById(bizEntityElement.getColumnID());
      if(column==null)
        throw new RuntimeException("查找实体【"+bizEntityElement.getBelongObject().getName()+"】中的字段【"+bizEntityElement.getName()+"】中对应的数据库对象列出错，找不到对应的列，数据库对象名称【"+databaseObject.getName()+"】");
      dbDataType= InitColumnInfoMethodGenerator.transDataType(column.getDataType());
      dbColumnName= column.getCode();
    }
    if(dbColumnName==null)
      dbColumnName="";
    if(field.getLabelID().equals(dbColumnName)==false)
      return false;
    if(isTypeEquals(field,dbDataType)==false)
      return false;
    return true;
  }

  private boolean isTypeEquals(IGspCommonField field, GspDbDataType dbDataType) {
    switch (field.getMDataType())
    {

      case String:
        return GspDbDataType.VarChar.equals(dbDataType);
      case Text:
       return  GspDbDataType.Clob.equals(dbDataType);
      case Integer:
        return GspDbDataType.Int.equals(dbDataType);
      case Decimal:
        return GspDbDataType.Decimal.equals(dbDataType);
      case Boolean:
        return GspDbDataType.Char.equals(dbDataType);
      case Date:
      return GspDbDataType.DateTime.equals(dbDataType);
      case DateTime:
        return GspDbDataType.DateTime.equals(dbDataType);
      case Binary:
        return GspDbDataType.Blob.equals(dbDataType);
        default:
          return false;
    }

  }
}
